#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 rambla.eu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.import os
import platform, os, sys, datetime
import unittest
import setup_environ
import json
import raws_json
from raws_json.raws_service import RawsService, Feed, Query
from raws_json.meta.service import MetaService
from raws_json.rass.service import RassService
from raws_json.meta.meta import *

class HardeningTest(unittest.TestCase):
    """ Some simple searches """
    
    @classmethod
    def setUpClass(cls):
        cls.meta_service = MetaService(username = setup_environ.TEST_USERNAME, password = setup_environ.TEST_PASSWORD, server = setup_environ.TEST_SERVER)
        cls.rass_service = RassService(username = setup_environ.TEST_USERNAME, password = setup_environ.TEST_PASSWORD, server = setup_environ.TEST_RASS_SERVER)
        # delete all existing content instances
        feed = cls.meta_service.getContentList()
        mf = Feed(feed)
        for e in mf.entries:
            cls.meta_service.deleteContent(e)
        # make sure files exist on the CDN
        status = cls.rass_service.getItemHeaderFromPath("oze.mp4")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "oze.mp4", local_path = setup_environ.LOCAL_FILE)
        status = cls.rass_service.getItemHeaderFromPath("oze.webm")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "oze.webm", local_path = setup_environ.LOCAL_FILE)
        status = cls.rass_service.getItemHeaderFromPath("oze.jpg")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "oze.jpg", local_path = setup_environ.LOCAL_FILE)
        status = cls.rass_service.getItemHeaderFromPath("test22/een/twee/oze.mp4")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "test22/een/twee/oze.mp4", local_path = setup_environ.LOCAL_FILE)
                
    def setUp(self):
        """ Delete all content for the account before running each test. """
        # delete all existing content instances
        feed = self.meta_service.getContentList()
        mf = Feed(feed)
        for e in mf.entries:
            self.meta_service.deleteContent(e)
    
    def test_create_non_ascii_tag(self):
        """ Create metadata content with non-ascii chars en meta elements. """
        f = FileObj(path = "/oze.mp4", media_type = "video", duration = 33, container = "mp4", bitrate = "800", width = "720", height = "360", 
                     frames = "322", framerate = "25", samplerate = "98")
        mc = MetaContent(name = "ono", file_objs = [f,], tags = [u"méë$é€",u"pèlèàùï"])
        meta_entry = self.meta_service.createContent(mc.to_entry())
        mc2 = MetaContent(entry = meta_entry)
        self.assertEqual(mc, mc2)
        self.assertEqual(2, len(mc2.tags))
        meta_entry = self.meta_service.updateContent(mc2.to_entry())
        mc3 = MetaContent(entry = meta_entry)
        self.assertEqual(mc, mc3)
        self.assertEqual(mc2, mc3)
        
    def test_create_non_ascii_meta(self):
        """ Create metadata content with non-ascii chars en meta elements. """
        f = FileObj(path = "/oze.mp4", media_type = "video", duration = 33, container = "mp4", bitrate = "800", width = "720", height = "360", 
                     frames = "322", framerate = "25", samplerate = "98")
        f2 = FileObj(path = "/oze.jpg")
        m = MetaObj(meta_name = "description", vocab = "dc", text = u"L’european shorthair, également appelé européen ou celtic shorthair, est une race de chat originaire d’Europe, représentant anobli des chats communs d’Europe. Ce rôle était détenu depuis le début du XXe siècle par le british shorthair, bien qu’il soit plus trapu que la plupart des chats communs européens, jusqu’en 1983 où l’european shorthair est reconnu par la Fédération internationale féline.\nÉvénements en cours : Printemps arabe · Crise de la dette publique dans la zone euro · Tournoi des six nations, 14 mars : mort du cinéaste français Pierre Schœndœrffer, à l’âge de 83 ans, 10 mars : aux élections législatives anticipées en Slovaquie, les sociaux-démocrates remportent la majorité absolue des sièges, une première dans le pays", lang = "fr")
        mc = MetaContent(name = "ono", file_objs = [f,f2,], meta_objs = [m,], thumb_used = "/oze.jpg")
        meta_entry = self.meta_service.createContent(mc.to_entry())
        mc2 = MetaContent(entry = meta_entry)
        # initial content obj must be the same as the one we got back from meta
        self.assertEqual(mc, mc2)
    
    def test_create_non_ascii_meta_name(self):
        """ Create metadata content with non-ascii chars en meta elements. """
        f = FileObj(path = "/oze.mp4", media_type = "video", duration = 33, container = "mp4", bitrate = "800", width = "720", height = "360", 
                     frames = "322", framerate = "25", samplerate = "98")
        f2 = FileObj(path = "/oze.jpg")
        m = MetaObj(meta_name = u"Déscription", vocab = "dc", text = u"L’european shorthair.", lang = "fr")
        mc = MetaContent(name = "ono", file_objs = [f,f2,], meta_objs = [m,], thumb_used = "/oze.jpg")
        meta_entry = self.meta_service.createContent(mc.to_entry())
        mc2 = MetaContent(entry = meta_entry)
        # initial content obj must be the same as the one we got back from meta
        self.assertEqual(mc, mc2)
    
    def test_create_content__file_doesnt_exist(self):
        """ Create content with only content.name + file set. """
        failed = False
        f = FileObj(path = "DezeFileBestaatNiet.mp4")
        mc = MetaContent(name = "DezeFileBestaatNiet", file_objs = [f,])
        try:
            meta_entry = self.meta_service.createContent(mc.to_entry())
        except Exception, e:
            failed = True
            print str(e)
        self.assertTrue(failed)

    def test_create_content__non_ascii_name(self):
        """ Create content with non-ascii chars in name => should be removed. """
        failed = False
        f = FileObj(path = "/oze.mp4")
        mc = MetaContent(name = "abcééédéééfgùùù", file_objs = [f,])
        try:
            meta_entry = self.meta_service.createContent(mc.to_entry())
        except Exception, e:
            failed = False
            print str(e)
        self.assertFalse(failed)

def suite():
   suite = unittest.TestSuite()
   suite.addTest(unittest.makeSuite(HardeningTest))
   return suite

if __name__=='__main__':
    unittest.main()
